-- Autocmds are automatically loaded on the VeryLazy event
-- Default autocmds that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/autocmds.lua
--
-- Add any additional autocmds here
-- with `vim.api.nvim_create_autocmd`
--
-- Or remove existing autocmds by their group name (which is prefixed with `lazyvim_` for the defaults)
-- e.g. vim.api.nvim_del_alocal ls = require("luasnip")
vim.api.nvim_create_autocmd("TextChangedI", {
  pattern = "*",
  callback = function()
    local line = vim.api.nvim_get_current_line()
    local col = vim.api.nvim_win_get_cursor(0)[2] + 1 -- 转换为 1-indexed

    -- 检测光标前两个字符是否为 ";;"
    if line:sub(math.max(1, col - 2), col - 1) == ";;" then
      vim.schedule(function() -- 异步执行防止递归触发
        -- 删除 ";;" 并替换为 ":<回车>"
        vim.api.nvim_set_current_line(line:sub(1, col - 3) .. line:sub(col))
        vim.api.nvim_input("<Esc>A:<CR>")
      end)
    end

    -- 检测光标前两个字符是否为 ",,"
    if line:sub(math.max(1, col - 2), col - 1) == ",," then
      vim.schedule(function() -- 异步执行防止递归触发
        -- 删除 ",," 并替换为 ",<回车>"
        vim.api.nvim_set_current_line(line:sub(1, col - 3) .. line:sub(col))
        vim.api.nvim_input("<Esc>A,<CR>")
      end)
    end

    -- 使用“；o”换行
    if line:sub(math.max(1, col - 2), col - 1) == ";o" then
      vim.schedule(function() -- 异步执行防止递归触发
        vim.api.nvim_set_current_line(line:sub(1, col - 3) .. line:sub(col))
        vim.api.nvim_input("<Esc>o")
      end)
    end

    if line:sub(math.max(1, col - 2), col - 1) == "jk" then
      vim.schedule(function()
        vim.api.nvim_set_current_line(line:sub(1, col - 3) .. line:sub(col))
        vim.api.nvim_input("<Esc>")
      end)
    end
  end,
})
